<template>
  <div ref="chartContainer" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  }
})

const chartContainer = ref(null)
let chart = null

const initChart = () => {
  if (!chartContainer.value) return
  
  chart = echarts.init(chartContainer.value)
  updateChart()
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart && chart.resize()
  })
}

const updateChart = () => {
  if (!chart || !props.chartData || props.chartData.length === 0) return
  
  // 反转数组以便按时间顺序显示
  const data = [...props.chartData].reverse()
  
  const months = data.map(item => item.month)
  const projects = data.map(item => item.projects)
  const papers = data.map(item => item.papers)
  const patents = data.map(item => item.patents)
  const awards = data.map(item => item.awards)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['项目', '论文', '专利', '奖项'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [
      {
        name: '项目',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: projects,
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '论文',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: papers,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '专利',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: patents,
        itemStyle: {
          color: '#E6A23C'
        }
      },
      {
        name: '奖项',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: awards,
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
  
  chart.setOption(option)
}

watch(() => props.chartData, () => {
  updateChart()
}, { deep: true })

onMounted(() => {
  initChart()
})
</script>